package com.pj.wisdomlogistics.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.entity.ApplyDetailInfo;
import com.pj.wisdomlogistics.mvp.contract.ApplyDetailContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.ApplyDetailPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.CustomAlertDialog;
import com.pj.wisdomlogistics.ui.view.NumberProgressDialog;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.ButtonGrayUtils;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.Log;
import com.pj.wisdomlogistics.utils.PdfDownload;
import com.pj.wisdomlogistics.utils.ShowPop;
import com.pj.wisdomlogistics.utils.ToSign;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;


public class ApplyDetailActivity extends MvpActivity<ApplyDetailPresenter> implements ApplyDetailContract.View,
        BaseActivity.RequestPermission, ShowPop.listener {

    @BindView(R.id.tv_apply_state)
    TextView mTvApplyState;
    @BindView(R.id.tv_apply_basic_info)
    TextView mTvApplyBasicInfo;
    @BindView(R.id.tv_apply_detail_dept)
    TextView mTvApplyDetailDept;
    @BindView(R.id.tv_apply_detail_call)
    TextView mTvApplyDetailCall;
    @BindView(R.id.tv_apply_detail_contacts)
    TextView mTvApplyDetailContacts;
    @BindView(R.id.tv_apply_detail_phone)
    TextView mTvApplyDetailPhone;
    @BindView(R.id.tv_apply_detail_apply_date)
    TextView mTvApplyDetailApplyDate;
    @BindView(R.id.rel_basic_info)
    RelativeLayout mRelBasicInfo;
    @BindView(R.id.tv_apply_detail_meeting_title)
    TextView mTvApplyDetailMeetingTitle;
    @BindView(R.id.tv_apply_detail_meeting_date)
    TextView mTvApplyDetailMeetingDate;
    @BindView(R.id.tv_apply_detail_meeting_time)
    TextView mTvApplyDetailMeetingTime;
    @BindView(R.id.tv_apply_detail_meeting_count)
    TextView mTvApplyDetailMeetingCount;
    @BindView(R.id.tv_apply_detail_rostrum_count)
    TextView mTvApplyDetailRostrumCount;
    @BindView(R.id.tv_apply_detail_normal_voice_count)
    TextView mTvApplyDetailNormalVoiceCount;
    @BindView(R.id.tv_apply_detail_stand_voice_count)
    TextView mTvApplyDetailStandVoiceCount;
    @BindView(R.id.apply_detail_music_on)
    TextView mApplyDetailMusicOn;
    @BindView(R.id.tv_apply_detail_big_agenda)
    TextView mTvApplyDetailBigAgenda;
    @BindView(R.id.tv_apply_detail_lift)
    TextView mTvApplyDetailLift;
    @BindView(R.id.tv_apply_detail_meeting_content)
    TextView mTvApplyDetailMeetingContent;
    @BindView(R.id.tv_apply_detail_banner)
    TextView mTvApplyDetailBanner;
    @BindView(R.id.tv_apply_detail_other)
    TextView mTvApplyDetailOther;
    @BindView(R.id.iv_apply_leader_sign)
    ImageView mIvApplyLeaderSign;
    @BindView(R.id.ll_apply_leader_sign)
    LinearLayout mLlApplyLeaderSign;
    @BindView(R.id.iv_apply_dept_stamp)
    ImageView mIvApplyDeptStamp;
    @BindView(R.id.ll_apply_dept_stamp)
    LinearLayout mLlApplyDeptStamp;
    @BindView(R.id.tv_apply_detail_manager_leader)
    TextView mTvApplyDetailManagerLeader;
    @BindView(R.id.tv_apply_detail_manager_charge_leader)
    TextView mTvApplyDetailManagerChargeLeader;
    @BindView(R.id.tv_apply_detail_manager_charger_phone)
    TextView mTvApplyDetailManagerChargerPhone;
    @BindView(R.id.tv_apply_detail_meeting_arrangement)
    TextView mTvApplyDetailMeetingArrangement;
    @BindView(R.id.tv_turn_portion)
    TextView mtvTurnPortion;
    @BindView(R.id.tv_turn_sign)
    TextView mtvTurnSign;
    @BindView(R.id.tv_turn_check)
    TextView mtvTurnCheck;
    @BindView(R.id.tv_apply_detail_meeting_arrangement1)
    TextView mTvApplyDetailMeetingArrangement1;
    @BindView(R.id.bt_on)
    Button mBtOn;
    @BindView(R.id.bt_off)
    Button mBtOff;
    @BindView(R.id.tv_leader_name)
    TextView mTvLeaderName;
    @BindView(R.id.tv_apply_detail_meeting_open_time)
    TextView mTvOpenTime;
    @BindView(R.id.tv_stamp_time)
    TextView mTvStampTime;
    @BindView(R.id.tv_apply_detail_manager_charge_leader_1)
    TextView mTvChargeAgree;
    @BindView(R.id.tv_turn_agree)
    TextView mTvTurnAgree;
    @BindView(R.id.tv_undo)
    TextView mTvUndo;
    @BindView(R.id.tv_apply_detail_meeting_place)
    TextView mTvPlace;


    private int meetingId;
    private int meetingTransactId;

    private String portionIds;

    private String currentStampUrl = "";
    private NumberProgressDialog mNumberProgressDialog;

    private String[] permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private boolean isCheck = false;
    private boolean isPortion = false;
    private CustomAlertDialog mCustomAlertDialog;

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        ultimateBar.setColorBar(ContextCompat.getColor(this, R.color.text_blue));

        meetingId = getIntent().getIntExtra(Cons.MeetingInfo.MEETING_ID, -1);
        meetingTransactId = getIntent().getIntExtra(Cons.TransactDetail.MEETING_TRANSACT_ID, -1);

        setRequestPermissionListener(this);

        mPresenter.findMeetingApplyDetail(meetingId != -1 ? meetingId : meetingTransactId);
        showProgressDialog();

        ShowPop.setListner(this);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_apply_detail;
    }

    @Override
    public boolean isApplyEventBus() {
        return true;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {
        if (eventCenter.getEventCode() == Cons.portion.PORTION_IDS) {
            portionIds = (String) eventCenter.getData();
            mPresenter.meetingApplyAllot(
                    meetingId != -1 ? meetingId : meetingTransactId,
                    MyApplication.userID,
                    "",
                    portionIds,
                    4,
                    0
            );
            showProgressDialog();
        }

    }


    @OnClick({R.id.iv_back, R.id.iv_apply_dept_stamp, R.id.tv_undo})
    public void onViewClicked(View mView) {
        switch (mView.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.iv_apply_dept_stamp:
                if (!checkPermissions(permission)) {
                    requestSystemPermissions(permission, 101);
                } else {
                    PdfDownload.pdfDownload(this, currentStampUrl);
                }
                break;
            case R.id.tv_undo:
                mCustomAlertDialog = new CustomAlertDialog.Builder(this)
                        .setMessage("确认撤销该申请单吗？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mPresenter.cancelMeetingApply(meetingId != -1 ? meetingId : meetingTransactId);
                                showProgressDialog();
                                mCustomAlertDialog.dismiss();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mCustomAlertDialog.dismiss();
                            }
                        }).create();
                mCustomAlertDialog.show();
                break;
        }

    }


    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this, errorMsg, 1000);
    }

    @Override
    public void onSuccess(final ApplyDetailInfo mInfo) {
        dismissProgressDialog();

        //已撤销的单子，或非首页、我的申请进来的单子，不展示撤销按钮
        if (mInfo.getCancel() == 1 || meetingId == -1 || !mInfo.getUserID().equals(MyApplication.userID)) {
            mTvUndo.setVisibility(View.GONE);
        }else{
            mTvUndo.setVisibility(View.VISIBLE);
        }

        currentStampUrl = mInfo.getCheck2Sign();

        RequestOptions options = new RequestOptions()
                .centerCrop()
                .priority(Priority.HIGH);


        //已签字
        if (mInfo.getCheck1() == 1) {
            mLlApplyLeaderSign.setVisibility(View.VISIBLE);
            Glide.with(this).load(mInfo.getCheck1Sign()).apply(options).into(mIvApplyLeaderSign);
        }

        if (mInfo.getCheck1() == 2) {
            mtvTurnSign.setVisibility(View.VISIBLE);
            mtvTurnSign.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck1Comments() + "    " + mInfo.getSignBackTime())));
        }

        //已盖章
        if (mInfo.getCheck2() == 1) {
            mLlApplyDeptStamp.setVisibility(View.VISIBLE);
            mTvStampTime.setText(mInfo.getSealTime());
            outer:
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                switch (MyApplication.user.getRoleId().get(i)) {
                    case Cons.RoleId.PORITION_HW:
                        ButtonGrayUtils.buttonGray(mBtOn, mBtOff, "同意", "驳回", mInfo.getState() <= 2);
                        break outer;
                    case Cons.RoleId.WYZG_HW:
                        ButtonGrayUtils.buttonGray(mBtOn, "分配", mInfo.getState() <= 3);
                        break outer;
                }
            }
        }

        //已审核
        if (mInfo.getCheck3() == 1) {
            mTvApplyDetailManagerLeader.setVisibility(View.VISIBLE);
            mtvTurnCheck.setVisibility(View.VISIBLE);
            mtvTurnCheck.setText("管理中心综合科：已同意" + "    " + mInfo.getReviewName() + "    " + mInfo.getRevieweTime());
        } else if (mInfo.getCheck3() == 2) {
            mtvTurnCheck.setVisibility(View.VISIBLE);
            mtvTurnCheck.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck3Comments() + "    " + mInfo.getRevieweBackTime())));
        }

        if (mInfo.getCheck4() == 1) {
            mTvChargeAgree.setVisibility(View.VISIBLE);
            mTvChargeAgree.setText("管理中心会务组：已同意" + "    " + mInfo.getLeaderName() + "    " + mInfo.getAllotTime());
        } else if (mInfo.getCheck4() == 2) {
            mTvTurnAgree.setVisibility(View.VISIBLE);
            mTvTurnAgree.setText(String.format(getResources().getString(R.string.apply_detail_turn_down,
                    mInfo.getCheck4Comments() + "    " + mInfo.getAllotBackTime())));
        }

        //已分配
        if (mInfo.getCheck5() == 1) {
            mTvApplyDetailManagerChargeLeader.setVisibility(View.VISIBLE);
            mTvApplyDetailManagerChargeLeader.setText("管理中心会务班长：已分配    " + mInfo.getAllotName() + "    " + mInfo.getPropertyTime());
//            mTvApplyDetailManagerChargeLeader.setText(String.format(getResources().getString(R.string.apply_detail_manager_charge_leader, mInfo.getLeaderName())));
//            mTvApplyDetailManagerChargerPhone.setVisibility(View.VISIBLE);
//            mTvApplyDetailManagerChargerPhone.setText(String.format(getResources().getString(R.string.apply_detail_phone,
//                    mInfo.getLeaderTel() + "    " + mInfo.getAllotTime())));
            mTvApplyDetailMeetingArrangement1.setVisibility(View.VISIBLE);
            mTvApplyDetailMeetingArrangement.setVisibility(View.VISIBLE);
            String arrangment = "";
            for (int i = 0; i < mInfo.getServerList().size(); i++) {
                arrangment += mInfo.getServerList().get(i).getDuty() + "  "
                        + mInfo.getServerList().get(i).getServerName() + "  "
                        + mInfo.getServerList().get(i).getTel() + "\n";
            }

            mTvApplyDetailMeetingArrangement.setText(arrangment);
        }


        mTvApplyDetailDept.setText(String.format(getResources().getString(R.string.apply_detail_dept, mInfo.getApplyDept())));
        mTvApplyDetailCall.setText(String.format(getResources().getString(R.string.apply_detail_call, mInfo.getOfficeTel())));
        mTvApplyDetailContacts.setText(String.format(getResources().getString(R.string.apply_detail_contacts, mInfo.getLinkman())));
        mTvApplyDetailPhone.setText(String.format(getResources().getString(R.string.apply_detail_phone, mInfo.getLinkmanTel())));
        mTvApplyDetailApplyDate.setText(String.format(getResources().getString(R.string.apply_detail_apply_date, mInfo.getApplyDate())));
        mTvApplyDetailMeetingDate.setText(String.format(getResources().getString(R.string.apply_detail_meeting_date, mInfo.getMeetingDate())));
        mTvApplyDetailMeetingTime.setText(String.format(getResources().getString(R.string.apply_detail_meeting_time, mInfo.getStartTime())));
        mTvApplyDetailMeetingCount.setText(String.format(getResources().getString(R.string.apply_detail_meeting_count, mInfo.getPeopleCount())));
        mTvApplyDetailRostrumCount.setText(String.format(getResources().getString(R.string.apply_detail_rostrum_count, mInfo.getRostrumCount())));
        mTvApplyDetailNormalVoiceCount.setText(String.format(getResources().getString(R.string.apply_detail_normal_voice_count, mInfo.getMikeCount())));
        mTvApplyDetailStandVoiceCount.setText(String.format(getResources().getString(R.string.apply_detail_stand_voice_count, mInfo.getStandMike())));
        mApplyDetailMusicOn.setText(String.format(getResources().getString(R.string.apply_detail_stand_voice_count, mInfo.getMusic() == 1 ? "是" : "否")));
        mTvApplyDetailBigAgenda.setText(String.format(getResources().getString(R.string.apply_detail_big_agenda, mInfo.getIsSchedule() == 1 ? "是" : "否")));
        mTvApplyDetailLift.setText(String.format(getResources().getString(R.string.apply_detail_meeting_islift, TextUtils.isEmpty(mInfo.getIsLift()) ? "无" : mInfo.getIsLift())));
        mTvApplyDetailMeetingContent.setText(String.format(getResources().getString(R.string.apply_detail_meeting_content, mInfo.getMeetingContent())));
        mTvApplyDetailBanner.setText(String.format(getResources().getString(R.string.apply_detail_banner, TextUtils.isEmpty(mInfo.getBanner()) ? "无" : mInfo.getBanner())));
        mTvApplyDetailOther.setText(String.format(getResources().getString(R.string.apply_detail_other, TextUtils.isEmpty(mInfo.getOtherService()) ? "无" : mInfo.getOtherService())));
        mTvApplyDetailMeetingTitle.setText(String.format(getResources().getString(R.string.apply_detail_meeting_title, mInfo.getMeetingRoomName())));
        mTvLeaderName.setText(mInfo.getSignName() + "    " + mInfo.getSignTime());
        mTvOpenTime.setText("开门时间：" + mInfo.getOpenTime());
        if(mInfo.getPlace() == null){
            mTvPlace.setText("会议地点：无");
        }else{
            mTvPlace.setText("会议地点：" + (mInfo.getPlace().equals("1") ? "政府大楼" : mInfo.getPlace().equals("2") ? "双和园" : "无"));
        }


        ////////////////////////以上为基本信息，以下为我的待办//////////////////////////////////
        if (mInfo.getState() == 0 && meetingTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if(MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.SIGN)){
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //签字
                            ToSign.sign(ApplyDetailActivity.this);
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            ShowPop.showTurnDown(ApplyDetailActivity.this, 8, mBtOff);
                        }
                    });
                }
            }
        }

        if (mInfo.getState() == 2 && meetingTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.CHECK_HW)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    mBtOn.setText("同意");

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //审核
                            mPresenter.meetingApplyReview(
                                    meetingId != -1 ? meetingId : meetingTransactId,
                                    MyApplication.userID,
                                    "",
                                    mInfo.getState()
                            );
                            isCheck = true;
                            showProgressDialog();
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            isCheck = false;
                            ShowPop.showTurnDown(ApplyDetailActivity.this, 9, mBtOff);
                        }
                    });

                }
            }
        }

        if ((mInfo.getState() == 3) && meetingTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.PORITION_HW)) {
                    mBtOn.setVisibility(View.VISIBLE);
                    mBtOff.setVisibility(View.VISIBLE);

                    mBtOn.setText("同意");

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //同意
                            mPresenter.meetingApplyKZ(
                                    MyApplication.userID,
                                    meetingId != -1 ? meetingId + "" : meetingTransactId + "",
                                    mInfo.getState() + "",
                                    ""
                            );
                        }
                    });

                    mBtOff.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //驳回
                            ShowPop.showTurnDown(ApplyDetailActivity.this, 10, mBtOff);
                        }
                    });
                }
            }
        }

        if ((mInfo.getState() == 4) && meetingTransactId != -1 && !MyApplication.isGzh) {
            for (int i = 0; i < MyApplication.user.getRoleId().size(); i++) {
                if (MyApplication.user.getRoleId().get(i).equals(Cons.RoleId.WYZG_HW)) {
                    mBtOn.setVisibility(View.VISIBLE);

                    mBtOn.setText("分配");

                    mBtOn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //分配
                            startActivity(PoritionActivity.class);
                        }
                    });

                }
            }
        }

    }

    @Override
    public void onSignSuccess(int isSign) {
        successToast(isSign == 0 ? "签字成功" : "驳回成功");
    }

    @Override
    public void onCheckSuccess() {
        successToast(isCheck ? "审核成功" : "驳回成功");
    }

    @Override
    public void portionSuccess(int isSign) {
        successToast("分配成功");
    }

    @Override
    public void agreeSuccess() {
        successToast("提交成功");
    }

    @Override
    public void onUndoSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this, "撤销成功", 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_APPLY));
        ActivityManagerUtil.create().finishActivity();
    }

    public void successToast(String toast) {
        dismissProgressDialog();
        CustomToast.showToast(this, toast, 1000);
        mPresenter.findMeetingApplyDetail(meetingId != -1 ? meetingId : meetingTransactId);
        mBtOn.setVisibility(View.GONE);
        mBtOff.setVisibility(View.GONE);
        EventBus.getDefault().post(new EventCenter<>(Cons.Other.MY_TRANSACT));
    }

    @Override
    public void onRequestResult(int requestCode, @android.support.annotation.NonNull String[] permissions, @android.support.annotation.NonNull int[] grantResults) {
        if (requestCode == 101) {
            if (!checkPermissions(permission)) {
                CustomToast.showToast(this, "您拒绝了相关权限的请求", 1000);
            } else {
                PdfDownload.pdfDownload(this, currentStampUrl);
            }
        }
    }


    @Override
    public void showTurnDown(int state, String text, int rating) {
        if (state == 8) {
            mPresenter.meetingApplySign(
                    meetingId != -1 ? meetingId : meetingTransactId,
                    MyApplication.userID,
                    null,
                    state,
                    text,
                    1);
        } else if (state == 9) {
            mPresenter.meetingApplyReview(
                    meetingId != -1 ? meetingId : meetingTransactId,
                    MyApplication.userID,
                    text,
                    state
            );
        } else if (state == 10) {
            mPresenter.meetingApplyKZ(
                    MyApplication.userID,
                    meetingId != -1 ? meetingId + "" : meetingTransactId + "",
                    state + "",
                    text
            );
        }
        showProgressDialog();
    }
}
